﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

//序列化工具
namespace SimpleCore.Tool
{
    public class SerializeTool
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="path">目标文件路径</param>
        /// <param name="go"></param>
        public static void Serialize(string path, object go)
        {
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter serializer = new BinaryFormatter();
                    serializer.Serialize(ms, go);
                    var data = ms.GetBuffer();
                    fs.Write(data, 0, data.Length);

                    ms.Dispose();
                }
            
                fs.Dispose();
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="path">加载的文件路径</param>
        /// <returns></returns>
        public static object Deserialize(string path)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            object go;
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                BinaryFormatter serializer = new BinaryFormatter();
                go = serializer.Deserialize(fs);
                fs.Dispose();
            }

            return go;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="path">加载的文件路径</param>
        /// <typeparam name="T">目标类型</typeparam>
        /// <returns></returns>
        public static T Deserialize<T>(string path)
        {
            return (T)Deserialize(path);
        }

        public static object Deserialize(byte[] bytes)
        {
            if (bytes == null)
            {
                return default;
            }

            object go;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                BinaryFormatter serializer = new BinaryFormatter();
                go = serializer.Deserialize(ms);
            }

            return go;
        }

        public static T Deserialize<T>(byte[] bytes)
        {
            return (T) Deserialize(bytes);
        }
    }
}